const axios = require('axios');

class SinaStockService {
  constructor() {
    // 新浪股票API基础URL
    this.baseUrl = 'http://money.finance.sina.com.cn/quotes_service/api/json_v2.php';
  }

  // 转换股票代码格式以适配新浪API
  convertSymbolForSina(symbol) {
    // 检查symbol是否定义
    if (!symbol) {
      throw new Error('symbol is not defined');
    }
    
    console.log(`Converting symbol for Sina: ${symbol}`);
    
    // 中国A股市场代码转换
    if (symbol.startsWith('000') || symbol.startsWith('002') || symbol.startsWith('300')) {
      // 深圳证券交易所股票
      const converted = 'sz' + symbol;
      console.log(`Converted ${symbol} to ${converted} (Shenzhen) for Sina`);
      return converted;
    } else if (symbol.startsWith('600') || symbol.startsWith('601') || symbol.startsWith('603') || symbol.startsWith('688')) {
      // 上海证券交易所股票
      const converted = 'sh' + symbol;
      console.log(`Converted ${symbol} to ${converted} (Shanghai) for Sina`);
      return converted;
    }
    
    // 其他代码保持不变
    console.log(`Keeping ${symbol} unchanged for Sina`);
    return symbol;
  }

  // 获取股票历史数据
  async getHistoricalData(symbol, interval = 'daily') {
    try {
      const convertedSymbol = this.convertSymbolForSina(symbol);
      console.log(`Fetching historical data from Sina for ${symbol} (converted to ${convertedSymbol})`);
      
      // 新浪API需要的参数
      const url = `${this.baseUrl}/CN_MarketData.getKLineData?symbol=${convertedSymbol}&scale=240&ma=no&count=300`;
      
      const response = await axios.get(url, {
        timeout: 15000, // 15秒超时
        headers: {
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
        }
      });

      // 检查响应数据
      if (!response.data) {
        throw new Error('No data returned from Sina API');
      }
      
      // 检查是否是错误响应
      if (response.data.error) {
        throw new Error(`Sina API error: ${response.data.error}`);
      }

      const rawData = response.data;
      if (!rawData || !Array.isArray(rawData) || rawData.length === 0) {
        throw new Error('No historical data returned from Sina API');
      }

      // 转换新浪API的数据格式为统一格式
      const historicalData = rawData.map(item => {
        // 新浪的数据格式: {day, open, high, low, close, volume}
        if (!item.day || item.open === undefined || item.high === undefined || 
            item.low === undefined || item.close === undefined || item.volume === undefined) {
          console.warn('Skipping invalid data item from Sina:', item);
          return null;
        }
        
        return {
          date: item.day, // 日期格式 'YYYY-MM-DD'
          open: parseFloat(item.open),
          high: parseFloat(item.high),
          low: parseFloat(item.low),
          close: parseFloat(item.close),
          volume: parseInt(item.volume)
        };
      }).filter(item => item !== null); // 过滤掉无效数据

      if (historicalData.length === 0) {
        throw new Error('No valid historical data after processing from Sina API');
      }

      // 按日期排序（从旧到新）
      historicalData.sort((a, b) => new Date(a.date) - new Date(b.date));

      console.log(`Successfully fetched ${historicalData.length} records from Sina for ${symbol}`);
      return historicalData;
    } catch (error) {
      console.error(`Error fetching historical data from Sina for ${symbol}: ${error.message}`);
      // 如果是网络错误或超时，提供更具体的错误信息
      if (error.code === 'ECONNABORTED' || error.code === 'ENOTFOUND') {
        throw new Error(`Network error when fetching from Sina: ${error.message}`);
      }
      throw new Error(`Error fetching historical data from Sina: ${error.message}`);
    }
  }

  // 获取股票实时数据
  async getRealTimeData(symbol) {
    try {
      const convertedSymbol = this.convertSymbolForSina(symbol);
      console.log(`Fetching real-time data from Sina for ${symbol} (converted to ${convertedSymbol})`);
      
      // 新浪实时行情API
      const url = `https://hq.sinajs.cn/list=${convertedSymbol}`;
      
      const response = await axios.get(url, {
        timeout: 10000, // 10秒超时
        headers: {
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
          'Referer': 'https://finance.sina.com.cn'
        }
      });

      // 检查响应数据
      if (!response.data) {
        throw new Error('No data returned from Sina API');
      }
      
      // 解析返回的数据
      // 格式类似: var hq_str_sz300015="爱尔眼科,12.480,12.590,12.530,12.620,12.420,12.530,12.480,761849,952805640,...";
      const dataStr = response.data;
      const match = dataStr.match(/"([^"]+)"/);
      if (!match) {
        throw new Error('Invalid data format from Sina API');
      }
      
      const dataParts = match[1].split(',');
      if (dataParts.length < 33) {
        throw new Error('Incomplete data from Sina API');
      }

      // 转换新浪API的数据格式为统一格式
      return {
        symbol: symbol, // 返回原始符号
        open: parseFloat(dataParts[1] || 0),
        high: parseFloat(dataParts[4] || 0),
        low: parseFloat(dataParts[5] || 0),
        price: parseFloat(dataParts[3] || 0),
        volume: parseInt(dataParts[8] || 0),
        latestTradingDay: new Date().toISOString().split('T')[0],
        previousClose: parseFloat(dataParts[2] || 0),
        change: parseFloat(dataParts[3] || 0) - parseFloat(dataParts[2] || 0),
        changePercent: dataParts[2] ? ((parseFloat(dataParts[3] || 0) - parseFloat(dataParts[2] || 0)) / parseFloat(dataParts[2] || 1) * 100) : 0
      };
    } catch (error) {
      console.error(`Error fetching real-time data from Sina for ${symbol}: ${error.message}`);
      // 如果是网络错误或超时，提供更具体的错误信息
      if (error.code === 'ECONNABORTED' || error.code === 'ENOTFOUND') {
        throw new Error(`Network error when fetching from Sina: ${error.message}`);
      }
      throw new Error(`Error fetching real-time data from Sina: ${error.message}`);
    }
  }
}

module.exports = new SinaStockService();